//
//  TTUIRefreshControl.swift
//  WeiBo
//
//  Created by 涂永江 on 2017/6/11.
//  Copyright © 2017年 涂永江. All rights reserved.
//

import UIKit

let viewHeight:CGFloat = 35

enum TTUIRefreshControlType {
    case normol
    case pull
    case loading
}
class TTUIRefreshControl: UIControl {

    override init(frame: CGRect) {
        super.init(frame: frame)
      setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //记录父视图ScrollerView
    var newScrollView:UIScrollView?
    //记录刷新的状态
    var refreshType:TTUIRefreshControlType? = .normol{
        didSet{
          
            if refreshType == .normol{
            //下拉刷新状态
               //让箭头恢复原状
                UIView.animate(withDuration: 0.1, animations: {
                    self.image.transform = CGAffineTransform.identity
                    
                }, completion: { (_) in
                    
                    if oldValue == .loading{
                        UIView.animate(withDuration: 0.5, animations: {
                        self.newScrollView?.contentInset.top -= self.frame.size.height
                        })
                    
                    }
                })
               //文字改变
                label.text = "下拉刷新"
                //停止风火轮
                indicatorView.stopAnimating()
                //显示箭头
                image.isHidden = false
                
              
            
            }else if refreshType == .pull
            {
             //松手就刷新
                //让箭头选择180度
                UIView.animate(withDuration: 0.5, animations: { 
                    self.image.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                })
                
                //文字变成 松手就刷新
                label.text = "松手就刷新"
                //
            
                
            }else if refreshType == .loading
            {
              // 让风火轮转起来
                  indicatorView.startAnimating()
              // 文字变成 松手就刷新
                  label.text = "正在刷新"
              // 隐藏箭头
                image.isHidden = true
                
                UIView.animate(withDuration: 0.5, animations: { 
                    
            self.newScrollView?.contentInset.top += self.frame.size.height
                }, completion: { (_) in
                    
                })
                
               sendActions(for: .valueChanged)
            }
        
            
        }
    
    }
    
    private lazy var image:UIImageView =  UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var label:UILabel = {
     
        let label = UILabel()
        label.text = "下拉刷新"
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.white
        label.textAlignment = .center
        return label
    }()
    
    private lazy var indicatorView:UIActivityIndicatorView = {
                let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
               return indicatorView
    }()
    
    func setUI()
    {
       self.frame.size.width = UIScreen.main.bounds.size.width
        self.frame.size.height = viewHeight
        self.frame.origin.y = -viewHeight
        backgroundColor = UIColor.red
        //设置uiimage
        addSubview(image)
        addSubview(label)
        addSubview(indicatorView)
    //设置约束
        image.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -40))
        addConstraint(NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        label.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: image, attribute: .trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: image, attribute: .centerY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: image, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: image, attribute: .centerY, multiplier: 1, constant: 0))
       
        
    }
    
    //添加到父视图回调
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        
        //拿到父视图,监听父视图的滚动
            //1.判断父视图是不是scrollview
        if newSuperview is UIScrollView
        {
    
            //添加kvo监听contentoffset滚动
            let newScrollView = newSuperview as! UIScrollView
           
                self.newScrollView = newScrollView
             newScrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
            
            
        }
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
//        print(newScrollView?.contentOffset.y)
        //拖拽是时的偏移量
        let contoffset = newScrollView?.contentOffset.y
       
        //临界点
        let criticalP = -((newScrollView?.contentInset.top)! + self.frame.size.height)
       
        
        //判断是否正在拖拽
        if (newScrollView?.isDragging)!
        {
         //如果是
           if contoffset! < criticalP && refreshType == .normol
           {
             //进入pull状态
             refreshType = .pull
            
           }else if contoffset! >= criticalP && refreshType == .pull
           {
             refreshType = .normol
            
           }
            
        }else
        {
        //如果不是
            if refreshType == .pull
            {
               refreshType = .loading
            }
        }
    }
    
    func endrerish(){
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2) {
          self.refreshType = .normol
        }
    }
    deinit {
        newScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
